package com.sjf.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjf.common.BaseContext;
import com.sjf.reggie.entity.AddressBook;
import com.sjf.reggie.mapper.AddressBookMapper;
import com.sjf.reggie.service.AddressBookService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author <huangtang>
 * @since 2022/4/27 10:40
 **/
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
    @Override
    public List<AddressBook> getList ( HttpSession session ) {
        Object userId = session.getAttribute ("user");
        QueryWrapper<AddressBook> wrapper = new QueryWrapper<> ();
        wrapper.lambda ().eq ( AddressBook::getUserId, userId );
        return list (wrapper);
    }

    @Override
    public boolean add ( AddressBook addressBook ) {
        Long userId = BaseContext.getCurrentId ();
        addressBook.setUserId ( userId );
        return save (addressBook);
    }

    @Override
    public boolean setDefaultAddress ( AddressBook addressBook ) {
        UpdateWrapper<AddressBook> wrapper = new UpdateWrapper<> ();
        //先将用户id下的所有地址的默认地址设置为0
        wrapper.lambda ().eq ( AddressBook::getUserId,BaseContext.getCurrentId ())
                        .set ( AddressBook::getIsDefault, 0 );
        update (wrapper);
        //再将当前地址设为默认地址
        wrapper.clear ();
        wrapper.lambda ().set ( AddressBook::getIsDefault, 1 )
                .eq (AddressBook::getId,addressBook.getId ());
        return update (wrapper);
    }

    @Override
    public boolean updateAddress ( AddressBook addressBook ) {
        return updateById (addressBook);
    }

    @Override
    public AddressBook getAddress () {

        QueryWrapper<AddressBook> wrapper = new QueryWrapper<> ();
        wrapper.lambda ().eq ( AddressBook::getUserId,BaseContext.getCurrentId ())
                .eq ( AddressBook::getIsDefault, 1 );
        return getOne (wrapper);
    }
}
